<!-- <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>模板引擎的原理1</title>
</head>
<body>
  <script type="text/html" id='tpl'>
    我叫{{name}}，今年{{age}}岁
  </script>
  <script>
    var obj = {name:'zs',age:20};
    //1.获取模板字符串
    var str = document.querySelector('#tpl').innerHTML;
    //2.找到模板字符串中所有 使用{{}}双花括号 标记起来的位置，在使用定义好的obj对象中的数据进行替换
    // 1)定义正则表达式
    // 使用()括号包裹 的部分会被额外保存成一个单元
    var reg = /{{(\w+)}}/;
    // 2)使用正则表达式找到str中对应的字符串
    // exec()方法 能够找到字符串中第一个能够和正则表达式匹配的字符串
    var ary = reg.exec(str);
    str = str.replace(ary[0],obj.name)
    var ary = reg.exec(str);
    str = str.replace(ary[0],obj.age)
    console.log(str)
  </script>
</body>
</html> -->

<!-- <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>模板引擎的原理2</title>
</head>
<body>
  <script type="text/html" id="tpl">
    我叫{{name}},今年{{age}}岁,我是个{{gender}}生
  </script>
  <script>
    var str = document.querySelector('#tpl').innerText;
    console.log(str);
    var obj = {name:'罗小黑',age:8,gender:'男'};
    var reg = /{{(\w+)}}/;
    var ary = reg.exec(str);
    while(ary = reg.exec(str)){
      str = str.replace(ary[0],obj[ary[1]]);
    }
    console.log(str)
  </script>
</body>
</html> -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>模板引擎的原理3</title>
</head>
<body>
  <script type="text/html" id="tpl">
    我叫{{name}},今年{{age}}岁,我是一个{{gender}}生
  </script>
  <script>
    //  var obj = {name:'罗小黑',age:8,gender:'男' };
    function template(id,obj){
      var str = document.getElementById(id).innerHTML;
      console.log(str)
      var reg = /{{(\w+)}}/
      var ary = reg.exec(str);
      while(ary = reg.exec(str)){
        str = str.replace(ary[0],obj[ary[1]]);
      };
      return str;
    }
    var s = template('tpl',{name:'罗小黑',age:8,gender:'男' })
    console.log(s)
  </script>
</body>
</html>